<?php

namespace api\modules\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 *
 * @property-read AdminUser|null $user
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    public $access_token = '';

    private $_user;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, '用户名或密码错误！');
            } elseif (!$user->validatePassword($this->password)) {
                $this->addError($attribute, '用户名或密码错误！');
            }
        }
    }

    /**
     * Logs in a AdminUser using the provided AdminUser and password.
     *
     * @return bool whether the AdminUser is logged in successfully
     */
    public function login()
    {
        /*if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 : 0);
        } else {
            return false;
        }*/
        if ($this->validate()) {
            // 登录成功， 设置过期时间
            $this->_user->expire = time() + Yii::$app->params['AUTH_ACCESS_TOKEN_EXPIRER_TIME'];

            $this->access_token = $this->_user->generateAccessToken();

            return true;
        } else {
            return false;
        }
    }

    /**
     * wxLogin
     *
     * @return bool whether the AdminUser is logged in successfully
     */
    public function wxLogin($openid = '', $uid = '')
    {
        $_user = $this->getUserByWechart($openid, $uid);
        if ($_user) {
            return Yii::$app->user->login($_user, $this->rememberMe ? 3600 * 24 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds AdminUser by [[username or phone]]
     *
     * @return AdminUser|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = AdminUser::findOne(['phone' => $this->username, 'status' => AdminUser::STATUS_ACTIVE]);
            if (!$this->_user) {
                $this->_user = AdminUser::findOne(['username' => $this->username, 'status' => AdminUser::STATUS_ACTIVE]);
            }
        }

        return $this->_user;
    }

    /**
     * Finds user by [[username or phone]]
     *
     * @return AdminUser|null
     */
    protected function getUserByWechart($openid, $uid)
    {
        if (!$openid) {
            $this->_user = null;
            return $this->_user;
        }

        if ($this->_user === null) {
            $this->_user = AdminUser::findOne(['phone' => $this->username, 'status' => AdminUser::STATUS_ACTIVE]);
            if (!$this->_user) {
                $this->_user = AdminUser::findOne(['username' => $this->username, 'status' => AdminUser::STATUS_ACTIVE]);
            }
        }

        return $this->_user;
    }
}
